package ch.hslu.weather;

import java.io.IOException;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnKeyListener;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class Main extends MapActivity {

	private MyMapView mapView;
	private WeatherAPI weatherAPI;
	private List<Overlay> mapOverlays;
	public static final int MENU_ADD = Menu.FIRST;
	public static final int MENU_REMOVE = Menu.FIRST + 1;
	private int mode = 0;
	public static final int MODE_OVERLAY_NONE = 0;
	public static final int MODE_OVERLAY_ADD = 1;
	public static final int MODE_OVERLAY_REMOVE = 2;

	public DBAdapter getDbAdapter() {
		return dbAdapter;
	}

	private Cursor cursor;
	private DBAdapter dbAdapter;
	private Handler mHandler = new Handler();

	public int getOverlayMode() {
		return mode;
	}

	protected Runnable updateResults = new Runnable() {
		public void run() {
			mapOverlays.clear();
			createClouds();
			mapView.invalidate();
			setProgressBarIndeterminateVisibility(false);
		}
	};

	public void setOverlayMode(int mode) {
		String abc = "aaa:bbb";
		String[] split = abc.split(":");
		System.out.println(split[0]);

		this.mode = mode;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.main);

		mapView = (MyMapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapView.setMapactivity(this);

		weatherAPI = new WeatherAPI(this);

		mapView.setOnKeyListener(new OnKeyListener() {

			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.KEYCODE_SEARCH) {
					Log.i("KEY", "SEARCH PRESSED");
				}
				return false;
			}
		});

		// mapView.setOnLongClickListener(new OnLongClickListener() {
		//			
		// @Override
		// public boolean onLongClick(View v) {
		// MyMapView mv = (MyMapView)v;
		// return false;
		// }
		// });

		mapOverlays = mapView.getOverlays();

		dbAdapter = new DBAdapter(this);
		dbAdapter.open();
	}

	public void addCloud(final GeoPoint p) {
		setProgressBarIndeterminateVisibility(true);
		Thread t = new Thread() {
			public void run() {

				String uri = "http://www.google.com/ig/api?weather=,,,"
						+ p.getLatitudeE6() + "," + p.getLongitudeE6()
						+ "&hl=en";

				Log.i("WEATHER URL", uri);

				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder db;
				String weather = "";
				String temp = "";
				String time = "";
				try {
					db = dbf.newDocumentBuilder();
					Document doc = db.parse(HttpGET.send(uri));
					NodeList nodes = doc.getElementsByTagName("condition");
					Node node = nodes.item(0).getAttributes().getNamedItem(
							"data");
					weather = node.getNodeValue();
					nodes = doc.getElementsByTagName("temp_c");
					node = nodes.item(0).getAttributes().getNamedItem("data");
					temp = node.getNodeValue();

					NodeList nodesTime = doc
							.getElementsByTagName("current_date_time");
					Node nodeTime = nodesTime.item(0).getAttributes()
							.getNamedItem("data");
					time = nodeTime.getNodeValue();

				} catch (ParserConfigurationException e) {
					Log.i("ERROR", "ParserConfigurationException");
				} catch (SAXException e) {
					Log.i("ERROR", "SAXException");
				} catch (IOException e) {
					Log.i("ERROR", "IOException");
				} catch (Exception e) {
					Log.i("ERROR", "SOMETHING ELSE");
				}

				dbAdapter.createWeather(temp, time, weather, p.getLatitudeE6(),
						p.getLongitudeE6());

				Log.i("Weather is", weather);

				mHandler.post(updateResults);
			}
		};
		t.start();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem item = menu.add(Menu.NONE, MENU_ADD, Menu.NONE, R.string.add);
		item.setIcon(android.R.drawable.ic_input_add);
		item = menu.add(Menu.NONE, MENU_REMOVE, Menu.NONE, R.string.remove);
		item.setIcon(android.R.drawable.ic_delete);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ADD:
			setOverlayMode(MODE_OVERLAY_ADD);
			Toast.makeText(this, getText(R.string.toast_add),
					Toast.LENGTH_SHORT).show();
			break;
		case MENU_REMOVE:
			setOverlayMode(MODE_OVERLAY_REMOVE);
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onStart() {
		mapOverlays.clear();
		createClouds();
		super.onStart();
	}

	private void createClouds() {
		cursor = dbAdapter.fetchWeather();
		if (cursor.moveToFirst()) {

			do {

				String time = cursor.getString(cursor
						.getColumnIndex(DBAdapter.WEATHER_KEY_TIME));
				String weather = cursor.getString(cursor
						.getColumnIndex(DBAdapter.WEATHER_KEY_WEATHER));
				String temp = cursor.getString(cursor
						.getColumnIndex(DBAdapter.WEATHER_KEY_TEMP));
				int lat = cursor.getInt(cursor
						.getColumnIndex(DBAdapter.WEATHER_KEY_LAT));
				int lon = cursor.getInt(cursor
						.getColumnIndex(DBAdapter.WEATHER_KEY_LON));
				int id = cursor.getInt(cursor
						.getColumnIndex(DBAdapter.WEATHER_KEY_ID));
				GeoPoint p = new GeoPoint(lat, lon);

				Drawable drawable = weatherAPI.getImage(weather, time);

				CloudOverlay cloud = new CloudOverlay(this, mapView, drawable
						.getCurrent(), temp, time, id);
				OverlayItem overlayitem = new OverlayItem(p, "", "");
				cloud.addOverlay(overlayitem);

				mapOverlays.add(cloud);
			} while (cursor.moveToNext());
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}